<template>
  <div v-if="pageStatus === 1">
    <ContentWrap>
      <!-- 搜索工作栏 -->
      <el-form ref="queryFormRef" :inline="true" :model="paramsData" class="-mb-10px" label-width="68px">
        <el-form-item label="合同名称" prop="name">
          <el-input v-model="paramsData.name" class="!w-300px" clearable placeholder="请输入合同名称" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="合同编号" prop="number">
          <el-input v-model="paramsData.number" class="!w-300px" clearable placeholder="请输入合同编号"
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="合同类别" prop="category">
          <el-select v-model="paramsData.category" class="!w-300px" clearable placeholder="请选择合同类别">
            <el-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="合同类型" prop="type">
          <el-select v-model="paramsData.type" class="!w-300px" clearable placeholder="请选择合同类别">
            <el-option v-for="item in contractTypeList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属部门" prop="department">
          <el-tree-select
            v-model="paramsData.department"
            class="!w-300px"
            :data="deptTree"
            filterable
            clearable
            :props="defaultProps"
            check-strictly
            default-expand-all
            placeholder="请选择所属部门"
            value-key="deptId"
          />
        </el-form-item>
        <el-form-item>
          <el-button v-hasPermi="['wise:contract:query']" @click="handleQuery">
            <Icon class="mr-5px" icon="ep:search" />
            搜索
          </el-button>
          <el-button @click="resetQuery">
            <Icon class="mr-5px" icon="ep:refresh" />
            重置
          </el-button>
          <el-button v-hasPermi="['wise:contract:create']" plain type="primary" @click="openForm(1)">
            <Icon class="mr-5px" icon="ep:plus" />
            新增
          </el-button>
          <el-button v-hasPermi="['wise:contract:export']" :loading="exportLoading" plain type="success"
            @click="handleExport">
            <Icon class="mr-5px" icon="ep:download" />
            导出
          </el-button>
        </el-form-item>
      </el-form>
    </ContentWrap>
    <!-- 列表 -->
    <ContentWrap>
      <el-table v-loading="loading" :data="tableData" @selection-change="tableSelectionChange">
        <el-table-column type="selection" width="30" />
        <template v-for="item in tableColumn" :key="item.prop">
          <el-table-column
            show-overflow-tooltip
            :width="item.width"
            :align="item.align ? item.align : 'center'" 
            :label="item.label"
            :prop="item.prop"
          >
            <template #default="scope">
              <div v-if="item.prop === 'number'" @click="openForm(2, scope.row.id)">
                <span style="color: #409eff;cursor: pointer;">{{ scope.row.number }}</span>
              </div>
              <div v-else-if="item.prop == 'category'">
                <span v-if="scope.row.category || scope.row.category === 0">{{ categoryList.find(item => item.id === scope.row.category).name }}</span>
                <span v-else>-</span>
              </div>
              <div v-else-if="item.prop == 'type'">
                <span v-if="scope.row.type || scope.row.type === 0">{{ contractTypeList.find(item => item.value === scope.row.type).label }}</span>
                <span v-else>-</span>
              </div>
              <div v-else-if="item.prop == 'createTime'">
                <p>创建时间：{{ scope.row.createTime ? formatDate(scope.row.createTime) : '-' }}</p>
                <p>更新时间：{{ scope.row.updateTime ? formatDate(scope.row.updateTime) : '-' }}</p>
              </div>
              <div v-else-if="item.prop == 'creator'">
                <p>创建：
                  {{ 
                      scope.row.creator ? 
                      userList.find(item => item.id == scope.row.creator)?.username + 
                      `（${userList.find(item => item.id == scope.row.creator)?.mobile}）` || 
                      '-' : '-' 
                  }}</p>
                <p>更新：
                  {{ 
                    scope.row.updater ? 
                    userList.find(item => item.id == scope.row.updater)?.username + 
                    `（${userList.find(item => item.id == scope.row.updater)?.mobile}）` || 
                    '-' : '-' 
                  }}</p>
              </div>
              <div v-else>
                {{ scope.row[item.prop] || (item.type === 'number' ? '0.00' : '-') }}
              </div>
            </template>
          </el-table-column>
        </template>

        <el-table-column :width="200" align="center" label="操作">
          <template #default="scope">
            <el-button v-hasPermi="['wise:contract:update']" link type="primary" @click="openForm(2, scope.row.id)">
              编辑
            </el-button>
            <el-button v-hasPermi="['wise:contract:delete']" link type="danger" @click="handleDelete(scope.row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>

      </el-table>


      <!-- 分页 -->
      <Pagination v-model:limit="paramsData.pageSize" v-model:page="paramsData.pageNo" :total="total" @pagination="getList" />
    </ContentWrap>
  </div>
  <div v-else>
    <ContractForm ref="formRef" />
  </div>
</template>
<script setup>
  import {ref, reactive, nextTick} from "vue"
  import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
  import { formatDate } from '@/utils/formatTime'
  import { defaultProps, handleTree } from '@/utils/tree'
  import * as DeptApi from '@/api/system/dept'
  import * as ContractApi from '@/api/viewsApi/contract'
  import ContractForm from './contractForm.vue'
  import download from '@/utils/download'
  import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
  const route = useRoute()
  const { wsCache } = useCache('sessionStorage')
  const userList = wsCache.get(CACHE_KEY.USER_LIST) || []
  const message = useMessage() // 消息弹窗
  const { t } = useI18n() // 国际化
  const formRef = ref() // 表单 Ref
  const contractTypeList = ref(getIntDictOptions(DICT_TYPE.CONTRACT_TYPE)) // 合同类型数据
  provide('contractTypeList', contractTypeList)
  const queryFormRef = ref() // 搜索的表单
  const exportLoading = ref(false) // 导出的加载中
  const paramsData = reactive({
    name: '', // 合同名称
    number: '', // 合同编号
    category: '', // 合同类别
    type: '', // 合同类型
    department: '', // 所属部门
    pageNum: 1,
    pageSize: 10,
    ids: [],
  })
  const categoryList = reactive([
    {id: 0, name: '主合同'},
    {id: 1, name: '子合同'},
  ])
  provide('categoryList', categoryList) // 合同类别数据
  const deptTree = ref() // 树形结构
  provide('deptTree', deptTree)

  const loading = ref(true) // 列表的加载中
  const total = ref(0) // 列表的总页数
  const tableData = ref([]) // 列表的数据
  const tableColumn = ref([
    { prop: 'number', label: '合同编号', align: 'center', width: 160},
    { prop: 'name', label: '合同名称', align: 'center', },
    { prop: 'category', label: '合同类别', align: 'center'},
    { prop: 'type', label: '合同类型', align: 'center'},
    { prop: 'amountWithTax', label: '合同金额（含税）', align: 'center', width: 180, type: 'number'},
    { prop: 'amountWithoutTax', label: '合同金额（不含税）', align: 'center', width: 180, type: 'number'},
    { prop: 'departmentName', label: '所属部门', align: 'center'},
    { prop: 'createTime', label: '时间', align: 'center', width: 230},
    { prop: 'creator', label: '操作人', align: 'center', width: 220},
  ]) // 表格的列
  const selectIds = ref([])
  const pageStatus = ref(1) // 1列表页  2新增编辑页

  const getList = async () => {
    loading.value = true
    try {
      const data = await ContractApi.getContractlList(paramsData)
      data.list.forEach(item => {
        if(item.department || item.department === 0){
          item.departmentName = findDeptNameById(deptTree.value, item.department)
        }else{
          item.departmentName = '-'
        }
        item.amountWithTax = (item.amountWithTax / 100).toFixed(2)
        item.amountWithoutTax = (item.amountWithoutTax / 100).toFixed(2)
      })
      tableData.value = data.list
      total.value = data.total
    } finally {
      loading.value = false
    }
  }
  provide('getList', getList)

  /** 搜索按钮操作 */
  const handleQuery = () => {
    paramsData.pageNo = 1
    getList()
  }

  /** 重置按钮操作 */
  const resetQuery = () => {
    queryFormRef.value.resetFields()
    handleQuery()
  }

  const openForm = (type, id) => {
    pageStatus.value = 2
    nextTick(() => {
      formRef.value.init(type, id)
    })
  }

  const goBack = () => {
    pageStatus.value = 1
    getList()
  }
  provide('goBack', goBack)

  /** 获得部门树 */
  const getTree = async () => {
    deptTree.value = []
    const data = await DeptApi.getSimpleDeptList()
    deptTree.value = handleTree(data)
  }
  const tableSelectionChange = (selection) => {
    selectIds.value = selection.map(item => item.id)
  }
  const handleExport = async () => {
    if(selectIds.value.length > 0){
      paramsData.ids = selectIds.value
    }
    try {
      // 导出的二次确认
      await message.exportConfirm()
      // 发起导出
      exportLoading.value = true
      const data = await ContractApi.exportContractl(paramsData)
      download.excel(data, '合同管理列表.xls')
    } catch {
    } finally {
      exportLoading.value = false
    }
  }
  function findDeptNameById(tree, id) {
    for (const node of tree) {
      if (node.id === id) {
        return node.name
      }
      if (node.children && node.children.length > 0) {
        const name = findDeptNameById(node.children, id)
        if (name) return name
      }
    }
    return ''
  }
  /** 删除按钮操作 */
  const handleDelete = async (id) => {
    try {
      // 删除的二次确认
      await message.delConfirm()
      // 发起删除
      await ContractApi.deleteContractl(id)
      message.success(t('common.delSuccess'))
      // 刷新列表
      await getList()
    } catch {}
  }
  /** 初始化 **/
  onMounted( async() => {
    await getTree()
    await getList()
    if(route.query.id){
      openForm(2, route.query.id)
    }
  })
</script>
<style lang="scss" scoped>

</style>
